import json
from flask import current_app, Blueprint, render_template, request
from app import db

module_tx_bbt = Blueprint('tie_xi_bbt', __name__, template_folder='templates')


@module_tx_bbt.route('/')
def production_volume():
    return render_template('manufacturing_info.html')


@module_tx_bbt.route('/api/manufacturing_info', methods=['GET'])
def api_for_production_volume():
    # akz_name = request.form['AKZ_NAME']
    akz_name = request.args.get('akz_name')
    data_dict = {}
    value_symbol_dict = {
        'A821GFG2': ['Z017', 'Z018'],
        'A821GRG2': ['Z017', 'Z018'],
        'A821GBG2': ['Z017', 'Z018'],
        'A821GSG2': ['Z017', 'Z018'],
        'A821DCS1': ['Z013'],
        'A821DCS2': ['Z013'],
    }
    filter_string = ''
    filter_list = []
    if akz_name in value_symbol_dict:
        symbol_list = value_symbol_dict[akz_name]
        num = len(symbol_list)
        if num > 1:
            tmp = []
            for i in range(num):
                value_symbol = akz_name + "._PLC.CVI." + symbol_list[i]
                value_symbol_with_quote = "'" + value_symbol + "'"
                filter_list.append(value_symbol)
                tmp.append(value_symbol_with_quote)
            value_symbols = ','.join(tmp)
            filter_string = ' IN (%s)' % value_symbols
        elif num == 1:
            filter_string = "='%s'" % symbol_list[0]
            filter_list.append(symbol_list[0])

    if filter_string:
        db_engine = db.get_engine(current_app, bind='IPS_T_Tiexi_Online')
        sql = "select id from p_values where value_symbol%s" % filter_string
        query_data = db_engine.execute(sql)
        id_list = []
        for row in query_data:
            id_list.append(row[0])
        id_len = len(id_list)
        if id_len > 0:
            for i in range(id_len):
                sql = "SELECT * FROM (SELECT value_num,time_stamp FROM p_value_archive WHERE value = %d " \
                      "ORDER BY id DESC) WHERE ROWNUM<=600 ORDER BY ROWNUM ASC" % id_list[i]
                query_data = db_engine.execute(sql)
                data_list = []
                for row in query_data:
                    tmp_dict = {}
                    for column, value in row.items():
                        if column == 'time_stamp':
                            tmp_dict[column] = value.strftime('%Y-%m-%d %H:%M:%S')
                        else:
                            tmp_dict[column] = value
                    data_list.append(tmp_dict)
                value_symbol = filter_list[i]
                data_dict[value_symbol] = data_list
    return json.dumps(data_dict)
